package com.sinoglobal.wallet.widget;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.sinoglobal.wallet.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

public class KeyboardUtil { 
	protected static final String TAG = KeyboardUtil.class.getSimpleName();
	protected static final int PASSWORD_LENGTH = 6;
	private boolean IsLibrary = false;//当Activity作为jar包使用是该值为true 否则为false
	public interface FinishListener{

		void onFinished(String inputStr);
		
		void onInputChar(int index);

		void deleteChar(int index);
		
	}
	private FinishListener mFinishListener;
	private KeyboardView keyboardView;
	private ImageButton keyboard_hide_btn;
	private Keyboard k2;// 数字键盘
	private EditText ed;
	private Context ctx;
	private boolean isPoint = false;
	
	private static String[] strings = { "0", "1", "2", "3", "4", "5", "6", "7",
		"8", "9" };
	private static List<String> labels;
	private static HashMap<String, Integer> keyMap = new HashMap<String, Integer>();
	static {
		labels = Arrays.asList(strings);
		for (int i = 0; i < strings.length; i++) {
			keyMap.put(strings[i], 48 + i);
		}
	}

	/**
	 * 随机集合
	 */
	public void randomList() {
		Collections.shuffle(labels);
		for (int i = 0; i < 9; i++) {
			k2.getKeys().get(i).label = labels.get(i);
			k2.getKeys().get(i).codes[0] = keyMap.get(labels.get(i));
		}
		k2.getKeys().get(10).label = labels.get(9);
		k2.getKeys().get(10).codes[0] = keyMap.get(labels.get(9));
	}

	@SuppressWarnings("unused")
	private int parseResLoc(String resStr) {
		String[] split = resStr.split("\\.");
		int resId = -1;
//		Log.d(TAG, "resStr:"+resStr);
		if(split.length==3){
			resId = MResource.getIdByName(ctx, split[1], split[2]);
		}
		return resId;
	}

	public KeyboardUtil(Context ctx, EditText edit, KeyboardView keyboard) {
		this.ctx = ctx;
		this.ed = edit;
		if(IsLibrary){
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
		}else{
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
		}
//		randomList();
		if (isPoint) {
			k2.getKeys().get(9).label = ".";
		} 
		keyboardView = keyboard;
		keyboardView.setKeyboard(k2);
		keyboardView.setEnabled(true);
		keyboardView.setPreviewEnabled(false);
		keyboardView.setOnKeyboardActionListener(listener);
	}
	
	public KeyboardUtil(Context ctx, EditText edit, boolean pointFlag) {
		this.ctx = ctx;
		Activity act = (Activity)ctx;
		isPoint = pointFlag;
		this.ed = edit;
		if(IsLibrary){
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
			keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
			keyboard_hide_btn = (ImageButton)act.findViewById(R.id.keyboard_hide_btn);
		}else{
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
			keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
			keyboard_hide_btn = (ImageButton)act.findViewById(R.id.keyboard_hide_btn);
		}
//		randomList();
		if (pointFlag) {
			k2.getKeys().get(9).label = ".";
		} 
		Log.d(TAG, "k2:"+k2+",keyboardView:"+keyboardView);
		hideActionListener();
		keyboardView.setKeyboard(k2);
		keyboardView.setEnabled(true);
		keyboardView.setPreviewEnabled(false);
		keyboardView.setOnKeyboardActionListener(listener);
	}
		
	public KeyboardUtil(Activity act, Context ctx, EditText edit) {
		this.ctx = ctx;
		this.ed = edit;
		if(IsLibrary){
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
			keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
			keyboard_hide_btn = (ImageButton)act.findViewById(R.id.keyboard_hide_btn);
		}else{
			k2 = new Keyboard(ctx, R.layout.wallet_pwd_symbols);
			keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
			keyboard_hide_btn = (ImageButton)act.findViewById(R.id.keyboard_hide_btn);
		}
//		randomList();
		if (isPoint) {
			k2.getKeys().get(9).label = ".";
		} 
		hideActionListener();
		keyboardView.setKeyboard(k2);
		keyboardView.setEnabled(true);
		keyboardView.setPreviewEnabled(false);
		keyboardView.setOnKeyboardActionListener(listener);
	}
	
	private void hideActionListener(){
		if(keyboard_hide_btn==null)
			return;
		keyboard_hide_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
			}
		});
	}
	
	//软键盘的点击事件
	private OnKeyboardActionListener listener = new OnKeyboardActionListener() {
		@Override
		public void swipeUp() {
			Log.d(TAG, "swipeUp");
		}
		@Override
		public void swipeRight() {
			Log.d(TAG, "swipeRight");
		}
		@Override
		public void swipeLeft() {
			Log.d(TAG, "swipeLeft");
		}
		@Override
		public void swipeDown() {
			Log.d(TAG, "swipeDown");
		}
		@Override
		public void onText(CharSequence text) {
//			Log.e(TAG, "onText:"+text);
		}
		@Override
		public void onRelease(int primaryCode) {
//			Log.d(TAG, "onRelease:"+primaryCode);
		}
		@Override
		public void onPress(int primaryCode) {
//			Log.d(TAG, "onPress:"+primaryCode);
		}
		@SuppressLint("ShowToast") @Override
		public void onKey(int primaryCode, int[] keyCodes) {
//			Log.d(TAG, "primaryCode:"+primaryCode);
			Editable editable = ed.getText();
			int start = ed.getSelectionStart();
			if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
				hideKeyboard();
			} else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
				if (editable != null && editable.length() > 0) {
					if (start > 0) {
						editable.delete(start - 1, start);
//						Log.d(TAG, "ed:"+ed);
						if(mFinishListener!=null)
							mFinishListener.deleteChar(start-1);
					}
				}
			} 
			else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {// 数字键盘切换
				keyboardView.setKeyboard(k2);
			} else if (primaryCode == 57419) { // go left
				if (start > 0) {
					ed.setSelection(start - 1);
				}
			} else if (primaryCode == 57421) { // go right
				if (start < ed.length()) {
					ed.setSelection(start + 1);
				}
			} else {
				if (primaryCode == 46 && !isPoint) {

				} else {
					String inputChar = Character.toString((char) primaryCode);
					editable.insert(start, inputChar);
					String inputStr = editable.toString();
					Log.d(TAG, "ed:"+ed+",inputStr:"+inputStr);
					if(mFinishListener!=null){
						mFinishListener.onInputChar(start);	
						mFinishListener.onFinished(inputStr);
					}
				}
			}
		}
	};
	
	//显示软键盘方法
	public void showKeyboard() {
		Log.d(TAG, "showKeyboard");
		keyboardView.setVisibility(View.VISIBLE);
		if(keyboard_hide_btn==null)
			return;
		keyboard_hide_btn.setVisibility(View.VISIBLE);
	}
	
	//完成
	public void hideKeyboard() {
		int visibility = keyboardView.getVisibility();
		if (visibility == View.VISIBLE) {
			keyboardView.setVisibility(View.GONE);
			if(keyboard_hide_btn==null)
				return;
			keyboard_hide_btn.setVisibility(View.GONE);
		}
	}

	public boolean getShowKeyboard() {
		if(keyboardView!=null && keyboardView.getVisibility()==View.VISIBLE){
			return true;
		}
		return false;
	}
	
	public void setFinishListener(FinishListener finishListener) {
		mFinishListener = finishListener;
	}
	
	/**
	   * 禁止Edittext弹出软件盘，光标依然正常显示。
	   */
	public void disableShowSoftInput(EditText et) {
		if (android.os.Build.VERSION.SDK_INT <= 10) {
			et.setInputType(InputType.TYPE_NULL);
		} else {
			Class<EditText> cls = EditText.class;
			Method method;
			try {
				method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
				method.setAccessible(true);
				method.invoke(et, false);
			} catch (Exception e) {
				// TODO: handle exception
			}

			try {
				method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
				method.setAccessible(true);
				method.invoke(et, false);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	  
}
